<script setup lang="ts">
import {useRoleViewStore} from "@/store/views/sys/admin/roleStore";
import {FormInstance, FormRules} from "element-plus";
import {RoleFormType} from "@/api/sys/admin/role/types";
import {addRoleApi} from "@/api/sys/admin/role";
import {storeToRefs} from "pinia";

const store = useRoleViewStore()
const {setAddVisible, getList} = store
const {addVisible, addForm} = storeToRefs(store)


// 编辑表单时规则验证
const ruleFormRef = ref<FormInstance>()
const loading = ref(false)

const rules :FormRules<RoleFormType>=({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
    {min: 1, max: 20, message: '昵称长度为1-20', trigger: 'blur'},
  ],
  code: [
    {required: true, message: '请输入编码', trigger: 'blur'},
    {min: 3, message: '编码名称不少于3个字符', trigger: 'blur'},
  ],
  sort: [
    {required: true, message: '请输入排序号', trigger: 'blur'},
  ]
})


// 提交编辑
async function submitAdd(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      addRoleApi(addForm.value).then(async () => {
        loading.value = true
        await getList()
        ElMessage.success('添加成功')
        setAddVisible(false)
      }).finally(() => {
        loading.value = false
      })
    } else {
      console.log('错误的字段', fields)
    }
  })

}

</script>

<template>
  <!-- 弹出框 :编辑-->
  <el-dialog draggable v-model="addVisible" title="添加用户" width="500" destroy-on-close>
    <el-form :model="addForm" label-suffix=":" label-width="80" ref="ruleFormRef" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model="addForm.name"/>
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="addForm.code"/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="addForm.sort"/>
      </el-form-item>
      <el-form-item label="状态">
        <el-radio-group v-model="addForm.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setAddVisible(false)">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitAdd(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>